package com.fruits.dao.impl;

import com.fruits.dao.CartDao;
import com.fruits.domain.Cart;
import com.fruits.util.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class CartDaoImpl implements CartDao {
    private QueryRunner queryRunner=new QueryRunner(DruidUtils.getDataSource());
    @Override
    public int add(int uid, Cart cart) {
        String sql="INSERT INTO shop(uid,fid,isStar,isCart) VALUES(?,?,?,?)";
        Object[] params={cart.getUid(),cart.getFid(),cart.isStar(),cart.isCart()};
        int add = 0;
        try {
            add = queryRunner.update(sql, params);
            return add;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public int update(int uid, Cart cart) {
        String sql="UPDATE shop SET isStar=?,isCart=? WHERE uid=? AND fid=?";
        Object[] params={cart.isStar(),cart.isCart(),cart.getFid(),uid};
        int add = 0;
        try {
            add = queryRunner.update(sql, params);
            return add;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int delete(int uid, int fid) {
        String sql="DELETE FROM shop WHERE uid=? AND fid=?";
        Object[] params={uid,fid};

        try {
          int  del = queryRunner.update(sql, params);
            return del;
            } catch (SQLException e) {
            throw new RuntimeException(e);
            }
        }


    @Override
    public Cart find(int uid, int fid) {
      String sql="SELECT * FROM shop WHERE uid=? AND fid=?";
      Object[] params={uid,fid};
      try {
          Cart cart = queryRunner.query(sql, new BeanHandler<Cart>(Cart.class), params);
          return cart;
      } catch (SQLException e) {
          throw new RuntimeException(e);
      }
    }

    @Override
    public List<Cart> findById(int uid) {
        String sql="SELECT * FROM shop WHERE uid=?";
        Object[] params={uid};
        try {
            List<Cart> cartList = queryRunner.query(sql, new BeanListHandler<Cart>(Cart.class), params);
            return cartList;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


}
